package it.bit.jlightqueryer.bl;

import it.bit.jlightqueryer.conn.Connection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Connection static manager
 * @author PerezDeQueya80
 */
public class Engine {
	private static Connection connection;

	/**
	 * Return main connection.
	 * @return main Connection
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		return connection;
	}

	/**
	 * Main static Connection setter
	 * @param connection
	 */
	public static void setConnection(Connection connection) {
		Engine.connection = connection;
	}

	/**
	 * Execute a simple query and return the result with headers and data
	 * @param sql
	 * @param maxrows Max rows to return. If is <= 0 return all rows
	 * @return ResultSetResult with headers and data
	 * @throws SQLException
	 */
	public static ResultSetResult query(String sql, int maxrows) throws SQLException {
		ResultSetResult result = new ResultSetResult();
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			st = getConnection().getConnection().prepareStatement(sql);
			rs = st.executeQuery();
			result.initMetaData(rs.getMetaData());
			int c = 0;
			while (rs.next() && (maxrows <= 0 || c < maxrows)) {
				for (int i = 0; i < result.data.length; i++) {
					result.data[i].add(rs.getObject(i+1));
				}
				c++;
			}
		}
		finally {
			if (rs!=null) rs.close();
			if (st!=null) st.close();
		}
		return result;
	}

	/**
	 * Execute a simple command, usually all except SELECT sql
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public static int execute(String sql) throws SQLException {
		int result = 0;
		PreparedStatement st = null;
		try {
			st = getConnection().getConnection().prepareStatement(sql);
			result = st.executeUpdate();
		}
		finally {
			if (st!=null) st.close();
		}
		return result;
	}

}
